import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import React, {useRef, useState} from 'react';
import {createTag, getAllTags} from "@/services/ant-design-pro/api";
import {Button, Input, Modal, Form, Radio, message} from "antd";
export const waitTimePromise = async (time: number = 100) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

const columns: ProColumns<API.Tag>[] = [
  {
    dataIndex: 'id',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '标签名称',
    dataIndex: 'tagName',
    copyable: true,
  },
  {
    title: '上传用户',
    dataIndex: 'uploadUser',
    render: uploadUser => { return uploadUser.username}
  },
  {
    title: '父级标签',
    dataIndex: 'isParent',
    valueType: 'select',
    valueEnum: {
      0: {
        text: '否'
      },
      1: {
        text: '是'
      }
    }
  },
  {
    title: '所属标签',
    dataIndex: 'parentTag',
    render: parentTag => {
      if (parentTag?.tagName) {
        return parentTag.tagName;
      } else {
        return '无'
      }
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    valueType: "dateTime"
  },
  {
    title: '状态',
    dataIndex: 'tagStatus',
    valueType: 'select',
    valueEnum: {
      0: {
        text: '正常',
        status: 'Success'
      },
      1: {
        text: '非法',
        status: 'Error'
      }
    }
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
        }}
      >
        编辑
      </a>,
      <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
        查看
      </a>,
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
  };

  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    const res = await createTag({
      data: {
        'tagName': values.tagName,
        'isParent': values.isParent,
        'parentId': values.parentId
      }
    });
    if (res?.data) {
      message.success('新增成功！');
    } else {
      message.error('新增失败！');
    }
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return <div>
    <Button type="primary" onClick={showModal}>新增标签</Button>
    <Modal title="新增标签" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="标签名称"
          name="tagName"
          rules={[{ required: true, message: '请输入标签名称!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<FieldType>
          label="是否是父级标签"
          name="isParent"
        >
          <Radio.Group>
            <Radio value="1"> 是 </Radio>
            <Radio value="0"> 否 </Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item<FieldType>
          label="父级标签id"
          name="parentId"
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
    <ProTable<API.Tag>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      request={async (params, sort, filter) => {
        console.log(sort, filter);
        await waitTime(2000);
        // 向后端发起请求
        const result = await getAllTags();
        return {
          data: result.data,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: result.code === 200,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: result.data.length,
        }
      }}
      editable={{
        type: 'multiple',
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      dateFormatter="string"
      headerTitle="标签表格"
    />
  </div>;
};
